package com.newtouch.avmarketing.api.controller;

import com.newtouch.avmarketing.api.entity.FileInfo;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

@Api(tags = "分片上传最终版")
@Controller
public class VideoController {
    private static HashMap<String, FileInfo> fileMap = new HashMap();
    // 模拟保存的位置
    private String savePath="E:\\fileItem";
    @RequestMapping(value = "/showVideo",method = RequestMethod.GET)
    public String show(){
        return "file";
    }

    @RequestMapping(value = "/file/uploadVideo",method = RequestMethod.POST)
    @ResponseBody
    public void fileUpload(FileInfo fileInfo, HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file"); // 通过参数名获取指定文件
        //创建分片
        File fileblob = new File(savePath+"\\"+fileInfo.getFileName()+"."+"blob");
        System.out.println("保存分片"+fileblob.getName());
        //保存分片  后面为true 表示在已有的文件进行追加。
        FileCopyUtils.copy(multipartFile.getInputStream(),new FileOutputStream(fileblob,true));
        //判断是否全部上传完成。
        if((fileInfo.getShardIndex()+1) == Math.ceil(fileInfo.getShardTotal())){
            System.out.println("上传完成，重命名");
            File saveFile = new File(savePath+"\\"+fileInfo.getFileName());
            //重命名操作
            fileblob.renameTo(saveFile);
            System.out.println("fileblob:"+fileblob);
//            fileblob.delete();
        }
        // 类似保存到数据库，这里简化下，直接放到map中。
        fileMap.put(fileInfo.getHasdCode(),fileInfo);

        System.out.println("fileMap:"+fileMap.toString());
    }
    @GetMapping("/getfile/{hashCode}")
    public FileInfo getFileInfoByCode(@PathVariable("hashCode") String hashCode){
        return fileMap.get(hashCode);
    }
}
